<?php
 
include 'db.php'; //database config and connection
 
//the switch gets the variables from the url with the corresponding case
switch(isset($_GET['action'])) {
	//add item from url variable	
    case "add_item":
		addToCart($_GET['id']);
        //AddProduct($_GET["id"]);
        //ShowCart();
		printCart();
	    break;	
}
 
 function addToCart($var){	 
	 //echo $var;
	 $result = mysql_query("select count(*) from cart where itemId = $var");
    $row = mysql_fetch_row($result);	
    $numRows = $row[0];
	echo 'NUMROWS : '.$numRows;
	if($numRows == 0){
		$item = mysql_query ("SELECT * FROM items where itemId = $var");
		$dbitems = mysql_fetch_row($item);
		$magDesc = $dbitems[1];
		$phCode = $dbitems[2];
		$iyot = "INSERT INTO cart(magDesc, phCode, itemId, qty) values('$magDesc', '$phCode', '$var', 1)";
		@mysql_query($iyot);
		echo $iyot;
	}else{
		 UpdateProduct($var);
	}
	header("Location: products.php");
	
	
 }
 
//function add product to cart
function AddProduct($itemId) {	
    $id_session = session_id();
 	//sessionId = '" . $id_session . "' and
    $result = mysql_query("select count(*) from cart where itemId = $itemId");
    $row = mysql_fetch_row($result);
	
    $numRows = $row[0]; 
    if($numRows == 0) {
        //This item doesn't exist in the users cart,
        //we will add it with an insert query
		
        @mysql_query("insert into cart(sessionId, magDesc, phCode, itemId, qty) values('" . $id_session . "', $magDesc, $phCode, $itemId, 1)");
        header("Location: products.php");		
    }
    else {
        //This item already exists in the users cart,
        //we will update it instead
        UpdateProduct($itemId);
    }
}

//function update product group if product is already in cart
 
//function update product +1 if product is already in cart 
function UpdateProduct($itemId) {
    $id_session = session_id();
    @mysql_query("update cart set qty = qty + 1 where sessionId = '" . $id_session . "' and itemId = $itemId");
    header("Location: products.php");
}

//display preview items on products page
function prepareSlides(){
	$sql = "SELECT * FROM items";
   if ($result=mysql_query($sql)) {
	   while ($row=mysql_fetch_array($result)) {
			echo '<div style="display: none; " class="productGroup" data-product-id="'.$row['phCode'].'">';
			echo '<div class="productShot"> <img src="img/sampleProduct.png" class="productImage" height="312" width="420"> </div>';
			echo '<div style="display: none; " class="productInfo">';
			echo '<div class="productTitle"><span class="economicaBold">'.$row['itemName'].'</span><br><font class="economicaBold" style="color:#00545c">'.$row['itemDesc'].'</font><p class="single-add"><a href="cart.php?action=add_item&id='.$row['itemId'].'">add this to cart</a></p></div>';
			echo '<div class="productDescription">';
			echo '<ul class="drop-down-menu">';
			echo '<li><a href="#" target="_blank"><font style="color:#00a7bc">›</font> Product picture (1.21 MB)</a></li>';
			echo '</ul>';
			echo '<div class="clear_all"></div>';
			echo '</div></div></div>';
	   }
   }else{
	   	echo mysql_error();
   }
}

//display item listing on products page
function showItems() {  
   $sql = "SELECT * FROM items";
   if ($result=mysql_query($sql)) {
	   while ($row=mysql_fetch_array($result)) {
		   //$totalItems += $row["qty"];
		   echo '<li>';
		   echo '<div class="productsLineUpPackBG" data-product-id="'.$row['phCode'].'">';
		   echo '<div class="productsLineUpPackImage">'.$row['itemDesc'].' </div> ';
		   echo '<div class="datacell dataWatts">'.$row['wattage'].'</div>';
		   echo '<div class="datacell dataCHW">'.$row['halogenWatt'].'</div>';
           echo '<div class="datacell dataSocket">'.$row['socket'].'</div>';
           echo '<div class="datacell dataIntense">'.$row['beamInt'].'</div>';
           echo '<div class="datacell dataAngle">'.$row['beamAngle'].'</div>';
           echo '<div class="datacell dataLifetime">'.$row['lifetime'].'</div>';
           echo '</div>';
		   echo '</li> '; 		   
	  }
   }else { echo mysql_error(); }   
}

function cartStatus(){
	$id_session = session_id();
    $totalItems = 0;
	/*
            WHERE cart.sessionId = '" . $id_session . "' */
	$sql = "SELECT *
            FROM cart
            INNER JOIN items
            WHERE cart.itemId = items.itemId ";
	 if ($result=mysql_query($sql)) {
      while ($row=mysql_fetch_array($result)) {
		   $totalItems += $row["qty"];
	  }
	  if($totalItems <= 0){
		  echo 'Your cart is empty';
	  }else{
		  echo 'You have '.$totalItems.' items in your cart.';
	  }
	 }
			
	return false;
}
 
function printCart() {
	$id_session = session_id();
    $totalCost = 0;
	//  WHERE cart.sessionId = '" . $id_session . "'";
	$sql = "SELECT * FROM cart INNER JOIN items ON cart.itemId = items.itemId";
	if($result=mysql_query($sql)){
		 while ($row=mysql_fetch_array($result)) {
			echo"<div class=\"itemRow\"><div class=\"itemWrap\">";
			echo "<strong>".$row['qty']."</strong> piece(s) of ";
        	echo "".$row['itemName']." ";
        	echo ' - ';
        	echo "".$row['itemDesc']." ";
        	echo "<strong>".$row['itemPrice']."</strong></div><div class=\"itemCtrl\"> <a title=\"remove this item\" class=\"decrease-item\" href=\"remove.php?id=".$row['cartId']."\">( remove ) </a>";
			echo ' <a class="add-item" title="add more of this item" href="cart.php?action=add_item&id='.$row['itemId'].'">(+)</a>'; // increment item button
			echo ' <a class="minus-item" title="subtract item quantity" href="minus.php?id='.$row['itemId'].'&cartId='.$row['cartId'].'&qty='.$row['qty'].'">(-)</a><div class="clear"></div></div><div class="clear"></div></div>'; //decrement item button
        //multiplay quantity and itemprice to get total of 1 product all together
        	$totalCost += $row["qty"] * $row["itemPrice"];			 
		 } // end while
		if($totalCost <= 0){
    		echo '<p>Your cart is empty.</p>';	
   		} else {
			echo '<div class="cartFooter"><div class="cartTotal">';			
			echo "Total: ";
    		//format of the totalcost 2 decimals and overall total
    		echo number_format($totalCost, 2, ".", ",");
			echo '</div><a class="printInvoice" href="print.php">Print</a></div><br> ';
   		}
	}else{
		echo mysql_error();
	} // end main if
	 
}

//select current user shopping cart and get total
function ShowCart(){
	
    $id_session = session_id();
    $totalCost = 0;
 
    $sql = "SELECT *
            FROM cart
            INNER JOIN items
            ON cart.itemId = items.itemId
            WHERE cart.sessionId = '" . $id_session . "'";
 	
    //open the table and print a header row
	echo '<form>'; //start with form as a header
    if ($result=mysql_query($sql)) {
      while ($row=mysql_fetch_array($result)) {
		echo"<div class=\"itemRow\"><div class=\"itemWrap\">";
		echo "<strong>".$row['qty']."</strong> piece(s) of ";
        echo "".$row['itemName']." ";
        echo ' - ';
        echo "".$row['itemDesc']." ";
        echo "<strong>".$row['itemPrice']."</strong></div><div class=\"itemCtrl\"> <a title=\"remove this item\" class=\"decrease-item\" href=\"remove.php?id=".$row['cartId']."\">( remove ) </a>";
		echo ' <a class="add-item" title="add more of this item" href="cart.php?action=add_item&id='.$row['itemId'].'">(+)</a>'; // increment item button
		echo ' <a class="minus-item" title="subtract item quantity" href="minus.php?id='.$row['itemId'].'&cartId='.$row['cartId'].'&qty='.$row['qty'].'">(-)</a><div class="clear"></div></div><div class="clear"></div></div>'; //decrement item button
        //multiplay quantity and itemprice to get total of 1 product all together
        $totalCost += $row["qty"] * $row["itemPrice"];
      }
   if($totalCost <= 0){
    echo '<p>Your cart is empty.</p>';	
   		} else {
			echo '<div class="cartFooter"><div class="cartTotal">';			
			echo "Total: ";
    //format of the totalcost 2 decimals and overall total
    echo number_format($totalCost, 2, ".", ",");
	echo '</div><a class="printInvoice" href="print.php">Print</a></div><br> ';
   	}
	echo '</form>';
	 }    else {
      echo mysql_error();
    }
}
?>